<template>
    <div class="container">
        <el-radio-group class="mgb20" v-model="labelPosition">
            <el-radio-button value="left">Left</el-radio-button>
            <el-radio-button value="right">Right</el-radio-button>
            <el-radio-button value="top">Top</el-radio-button>
        </el-radio-group>
        <el-form ref="formRef" :rules="rules" :model="applicationForm" label-width="120px"
            :label-position="labelPosition">
            <el-row :gutter="50">
                <el-col :span="10">
                    <el-form-item label="报考驾照类型" prop="licence">
                        <el-select v-model="applicationForm.licence" placeholder="Select" style="width: 240px">
                            <el-option v-for="item in licenceOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="身份证" prop="student.studentIdentityId">
                        <el-input v-model="applicationForm.student.studentIdentityId"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="student.studentName">
                        <el-input v-model="applicationForm.student.studentName"></el-input>
                    </el-form-item>
                    <el-form-item label="年龄" prop="student.studentAge">
                        <el-input-number v-model="applicationForm.student.studentAge" :min="18" :max="100" />
                    </el-form-item>
                    <el-form-item label="性别" prop="student.studentSex">
                        <el-select v-model="applicationForm.student.studentSex" placeholder="请选择">
                            <el-option key="男" label="男" value="男"></el-option>
                            <el-option key="女" label="女" value="女"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="电话号码" prop="student.studentPhone">
                        <el-input v-model="applicationForm.student.studentPhone"></el-input>
                    </el-form-item>
                    <el-form-item label="请选择教练" prop="coach">
                        <el-select v-model="applicationForm.coach" placeholder="请选择" @click="coachVisible = true">
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit(formRef)">表单提交</el-button>
                        <el-button @click="onReset(formRef)">重置表单</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-dialog v-model="coachVisible" width="600">
            <template #header="{ titleId, titleClass }">
                <div class="my-header">
                    <h4 :id="titleId" :class="titleClass">设置偏好，系统将会为您推荐教练</h4>
                </div>
            </template>
            <el-form-item label="教练性别">
                <el-select v-model="coachPreference.sex" placeholder="请选择教练性别">
                    <el-option key="无要求" label="无要求" value="无要求"></el-option>
                    <el-option key="男" label="男" value="男"></el-option>
                    <el-option key="女" label="女" value="女"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="教练年龄">
                <el-form-item>
                    <el-input-number v-model="coachPreference.age1" :min="18" :max="80" />
                    <el-icon>
                        <SemiSelect />
                    </el-icon><el-icon>
                        <ArrowRightBold />
                    </el-icon>
                    <el-input-number v-model="coachPreference.age2" :min="18" :max="80" />
                </el-form-item>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Check" @click="recommend()">确定</el-button>
                <el-button icon="Refresh" @click="reset()">重置</el-button>
            </el-form-item>
            <h4 v-show="showCoachList">以下是为您推荐的教练：</h4>
            <el-table v-show="showCoachList" :data="filteredCoach">
                <el-table-column property="coachName" label="姓名" width="150" /> <!-- 假设“姓名”字段在数据中为“name” -->
                <el-table-column property="coachSex" label="性别" width="200" />
                <el-table-column property="coachAge" label="年龄" />
                <el-table-column type="action" label="操作" width="270">
                    <template v-slot="{ row }">
                        <el-button type="primary" size="mini" @click="chooseCoach(row)">
                            选择
                        </el-button>

                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="forms">
import { onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormProps, FormRules } from 'element-plus';

import type { coachItemData } from '@/api/coach';
import * as coachApi from '@/api/coach';
import type { applicationItemData } from '@/api/aplication';
import * as applicationApi from '@/api/aplication';
import { studentItemData } from '@/api/student';
import * as licenceApi from '@/api/licence';
import { licenceItemData } from '@/api/licence';

const coachVisible = ref(false)
const showCoachList = ref(false)
const filteredCoach = ref<coachItemData[]>([]);
const coachPreference = ref({ sex: '', age1: 18, age2: 80 });
const licenceOptions = ref<Array<{ value: string; label: string }>>([
    { value: '', label: '加载中...' }
]);

const labelPosition = ref<FormProps['labelPosition']>('right')
const rules: FormRules = {
    "student.studentPhone": [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
    "student.studentSex": [{ required: true, message: '请选择性别', trigger: 'blur' }],
    'student.studentAge': [{ required: true, message: '请输入年龄', trigger: 'blur' }],
    "student.studentName": [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    "student.studentIdentityId": [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
    licence: [{ required: true, message: '请选择驾照类型', trigger: 'blur' }],
    coach: [{ required: true, message: '请选择教练', trigger: 'blur' }],
};
const formRef = ref<FormInstance>();;
// 定义初始的空对象
const initialStudentData: studentItemData = {
    studentId: 0,
    studentName: '',
    studentIdentityId: '',
    studentSex: '男',
    studentAge: 18,
    studentPhone: ''
};
// 初始化 studentForm 为初始的空对象
const studentForm = ref<studentItemData>({ ...initialStudentData });
// 获取并解析 localStorage 中的 studentInfo
const storedStudentInfo = localStorage.getItem("studentInfo");
if (storedStudentInfo) {
    try {
        studentForm.value = JSON.parse(storedStudentInfo) as studentItemData;
    } catch (e) {
        console.error("Failed to parse studentInfo from localStorage", e);
    }
}
const applicationForm = ref<applicationItemData>({
    applicationId: '',
    applicationTime: '',
    applicationPreference: '',
    applicationFinished: '',
    progressId: 0,
    coachId: 0,
    studentId: 0,
    licenceId: 0,
    progress: null,
    coach: null,
    student: studentForm.value,
    licence: null
});

const generateData = () => {
    const data = []
    for (let i = 1; i <= 15; i++) {
        data.push({
            key: i,
            label: `Option ${i}`,
            disabled: i % 4 === 0,
        })
    }
    return data
}

const transferData = ref(generateData())
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
    // 表单校验
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            console.log(applicationForm.value);
            ElMessage.success('提交成功！');
        } else {
            return false;
        }
    });
};
// 重置
const onReset = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};
const recommend = async () => {
    // const response = await coachApi.getCoachBySexOrAge(coachPreference.value.sex,coachPreference.value.age1,coachPreference.value.age2);
    const response = await coachApi.fetchData();
    console.log(response.data.list);
    filteredCoach.value = response.data.list;
    showCoachList.value = true;
}
const reset = () => {
    coachPreference.value.sex = '';
    coachPreference.value.age1 = 18;
    coachPreference.value.age2 = 80;
    showCoachList.value = false;
}
const chooseCoach = (row) => {
    applicationForm.value.coach = row;
    console.log("chooseCoach : " + applicationForm);
    coachPreference.value.sex = '';
    coachPreference.value.age1 = 18;
    coachPreference.value.age2 = 80;
    showCoachList.value = false;
    coachVisible.value = false;
}
const initLicenceOption = async () => {
    try {
        const resp = await licenceApi.fetchData();
        licenceOptions.value = resp.data.licences.map((element: any) => ({
            value: element.licenceId,
            label: element.licenceType
        }));
    } catch (error) {
        console.error(error);
    }
};

onMounted(() => {
    initLicenceOption();
});

</script>